package edu.ncst.baseweb.controller.borrow;

import cn.wintersun.basecommon.common.Result;
import edu.ncst.baseweb.dao.BorrowRecord;
import edu.ncst.baseweb.mapper.BorrowRecordMapper;
import edu.ncst.baseweb.mapper.EquMapper;
import edu.ncst.baseweb.service.intrer.borrow.BorrowRecordService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;

/**
 * 设备借用/设备借用记录
 */
@RestController
@RequestMapping("/admin/borrow/borrecord")
@PreAuthorize("hasAuthority('4')")
public class BorrowReccrdController {

    @Autowired private BorrowRecordService borrowRecordService;

    @Autowired
    private EquMapper equMapper;

    @Autowired
    private BorrowRecordMapper borrowRecordMapper;


    //借用记录列表
    @RequestMapping(value = "list",method = RequestMethod.POST)
    public Result<IPage<BorrowRecord>> list(@RequestBody BorrowRecord borrowrecord){

        return  borrowRecordService.list(borrowrecord);
    }
    //归还
    @RequestMapping(value = "repay",method = RequestMethod.POST)
    public Result<Object> repay(@RequestBody BorrowRecord borrowRecord){
        try {
            return borrowRecordService.repay(borrowRecord);
        } catch (Exception e) {
            return Result.failure(500, e.getMessage());
        }
    }
    @GetMapping("/view")
    public ResponseEntity<StreamingResponseBody> getImage(@RequestParam("id") String id, @RequestParam("indexid") String indexid ) throws IOException {

        //通过穿过来的借用记录的id获取到equid
        String equId = borrowRecordMapper.getEquidById(id);
        try {
            //展示图片
            if (Objects.equals(indexid, "0")){
                String imageName =  equMapper.getImageName(equId);
                String imageUrl = equMapper.getImageUrl(equId);
                //图片不存在
                if (imageName == null || imageName.isEmpty()) {
                    StreamingResponseBody responseBody = outputStream -> {
                        String errorMessage = "图片不存在";
                        outputStream.write(errorMessage.getBytes());
                    };
                    return ResponseEntity.status(HttpStatus.NOT_FOUND)
                            .contentType(MediaType.TEXT_PLAIN)
                            .body(responseBody);
                }
                Path imagePathObj = Paths.get(imageUrl);
                Resource imageResource = new FileSystemResource(imagePathObj.toFile());

                StreamingResponseBody responseBody = outputStream -> {
                    try (InputStream inputStream = imageResource.getInputStream()) {
                        IOUtils.copy(inputStream, outputStream);
                    } catch (Exception e) {
                        // 处理文件读取错误的情况
                    }
                };


                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.IMAGE_JPEG); // 或者 MediaType.IMAGE_PNG，取决于图片类型
                headers.setContentDispositionFormData("attachment", imageName);

                return ResponseEntity.ok()
                        .headers(headers)
                        .body(responseBody);
                //展示视频
            } else if (Objects.equals(indexid, "1")) {
                String videoName =  equMapper.getVideoName(equId);
                String videoUrl = equMapper.getVideoUrl(equId);
                if (videoName == null || videoName.isEmpty()) {
                    StreamingResponseBody responseBody = outputStream -> {
                        String errorMessage = "视频不存在";
                        outputStream.write(errorMessage.getBytes());
                    };
                    return ResponseEntity.status(HttpStatus.NOT_FOUND)
                            .contentType(MediaType.TEXT_PLAIN)
                            .body(responseBody);
                }

                Path videoPathObj = Paths.get(videoUrl);
                Resource videoResource = new InputStreamResource(Files.newInputStream(videoPathObj));

                StreamingResponseBody responseBody = outputStream -> {
                    try(InputStream inputStream = videoResource.getInputStream()) {
                        IOUtils.copy(inputStream, outputStream);
                    } catch (Exception e) {
                        // 处理文件读取错误的情况
                    }
                };


                // 设置响应头
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                headers.setContentDispositionFormData("attachment",videoName);

                // 返回视频数据
                return ResponseEntity.ok()
                        .headers(headers)
                        .body(responseBody);
            }
            //展示pdf文件
            else if (Objects.equals(indexid, "2")) {

                String pdfName = equMapper.getFileName(equId);
                String pdfUrl = equMapper.getFileUrl(equId);
                if (pdfName == null || pdfName.isEmpty()) {
                    StreamingResponseBody responseBody = outputStream -> {
                        String errorMessage = "PDF文件不存在";
                        outputStream.write(errorMessage.getBytes());
                    };
                    return ResponseEntity.status(HttpStatus.NOT_FOUND)
                            .contentType(MediaType.TEXT_PLAIN)
                            .body(responseBody);
                }

                Path pdfPathObj = Paths.get(pdfUrl);
                Resource pdfResource = new InputStreamResource(Files.newInputStream(pdfPathObj));

                StreamingResponseBody responseBody = outputStream -> {
                    try(InputStream inputStream = pdfResource.getInputStream()) {
                        IOUtils.copy(inputStream, outputStream);
                    } catch (Exception e) {
                        // 处理文件读取错误的情况
                    }
                };

                // 设置响应头
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_PDF);
                headers.setContentDispositionFormData("attachment", pdfName);

                // 返回PDF文件数据
                return ResponseEntity.ok()
                        .headers(headers)
                        .body(responseBody);

            }
        }catch (IOException e){
            e.printStackTrace();
        }
        // 若发生异常，则返回适当的响应
        return ResponseEntity.notFound().build();
    }
}
